﻿#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Class.Web.Mvc;
using Telerik.Web.Mvc;
using ThuySan.Areas.Backend.Models;
using ThuySan.Bussiness;
using ThuySan.Models;

#endregion

namespace ThuySan.Areas.Backend.Controllers
{
    [Authorize]
    public class ProductController : BaseController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        #region Product

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GetList()
        {
            return View(new GridModel(_unitOfWork.ProductRepository.Select().Select(c => new
            {
                c.ProductId,
                c.Name,
                c.Viewer,
                c.Priority,
                CName = c.Category.Name,
                Status = c.Status ?? false ? "checked" : "",
                IsReduced = c.IsReduced ?? false ? "checked" : "",
                IsVisibled = c.IsVisibled ?? false ? "checked" : "",
            })));
        }

        [HttpPost]
        public ActionResult Delete(string id)
        {
            if (id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s where int.TryParse(s1, out guid) select int.Parse(s1)).ToList();

                if (_unitOfWork.ProductRepository.CheckDeleteProduct(list))
                {
                    _unitOfWork.ProductRepository.Delete(list, "Products", DeleteResource);
                }
            }
            return Content("");
        }

        public ActionResult Add()
        {
            ViewBag.Categories = _unitOfWork.CategoryRepository.Select().ToList().Select(c => new SelectListItem
            {
                Text = c.Name,
                Value = c.CategoryId + ""
            });
            return View(new ProductModel
                            {
                                IsVisibled = true,
                                Status = true
                            });
        }

        [ValidateInput(false), HttpPost]
        public ActionResult Add(ProductModel productModel)
        {
            if (productModel.IsReduced)
            {
                if (!productModel.PromotionalPrice.HasValue)
                    ModelState.AddModelError("PromotionalPrice", "This Promotional Price field is required");
            }
            if (ModelState.IsValid)
            {
                Product product = productModel;
                if (_unitOfWork.ProductRepository.CheckInsertProduct(product))
                {
                    Exception exception;
                    product.PageUrl = ConvertToUnSign(string.IsNullOrEmpty(productModel.PageUrl)
                                                          ? product.Name
                                                          : product.PageUrl);
                    product.LastModified = DateTime.Now;
                    _unitOfWork.ProductRepository.Insert(product, out exception);
                    if (exception == null)
                    {
                        product.AvatarImage = SaveResource("thumbnail", "Products", product);
                        _unitOfWork.AcceptChanges();

                        return RedirectToAction("Edit", new
                        {
                            id = product.ProductId
                        });
                    }
                    ModelState.AddModelError("error", exception.StackTrace);
                }
            }
            ViewBag.Categories = _unitOfWork.CategoryRepository.Select().ToList().Select(c => new SelectListItem
            {
                Text = c.Name,
                Value = c.CategoryId + ""
            });
            return View(productModel);
        }

        public ActionResult Edit(string id)
        {
            int guid;
            if (int.TryParse(id, out guid))
            {
                Product product = _unitOfWork.ProductRepository.SelectbyId(guid);
                if (product != null)
                {
                    ProductModel productModel = product;
                    ViewBag.Categories = _unitOfWork.CategoryRepository.Select().ToList().Select(c => new SelectListItem
                    {
                        Text = c.Name,
                        Value = c.CategoryId + ""
                    });
                    return View(productModel);
                }
            }
            return RedirectToAction("Index");
        }

        [ValidateInput(false), HttpPost]
        public ActionResult Edit(ProductModel productModel)
        {
            //if (productModel.IsReduced)
            //{
            //    if (!productModel.PromotionalPrice.HasValue)
            //        ModelState.AddModelError("PromotionalPrice", "This Promotional Price field is required");
            //}
            if (ModelState.IsValid)
            {
                Product product = _unitOfWork.ProductRepository.SelectbyId(productModel.ProductId);
                productModel.Update(product);
                if (_unitOfWork.ProductRepository.CheckUpdateProduct(product))
                {
                    Exception exception;
                    product.PageUrl = ConvertToUnSign(string.IsNullOrEmpty(productModel.PageUrl)
                                                          ? product.Name
                                                          : product.PageUrl);
                    product.LastModified = DateTime.Now;
                    _unitOfWork.ProductRepository.Update(product, out exception);
                    if (exception == null)
                    {
                        product.AvatarImage = SaveResource("thumbnail", "Products", product.AvatarImage, product);
                        _unitOfWork.AcceptChanges();

                        return RedirectToAction("Index");
                    }
                    ModelState.AddModelError("error", exception.StackTrace);
                }
            }
            ViewBag.Categories = _unitOfWork.CategoryRepository.Select().ToList().Select(c => new SelectListItem
            {
                Text = c.Name,
                Value = c.CategoryId + ""
            });
            return View(productModel);
        }

        #endregion

        #region Tag

        public ActionResult ProductTags(int id)
        {
            List<int?> ids = _unitOfWork.ProductTagRepository.Select(c => c.ProductId == id).Select(c => c.TagId).ToList();
            string first = "";
            StringBuilder stringBuilder = new StringBuilder();
            foreach (int? i in ids)
            {
                stringBuilder.AppendFormat("{0}{1}", first, i);
                if (string.IsNullOrEmpty(first))
                    first = ",";
            }
            ViewBag.Ids = stringBuilder.ToString();
            return PartialView(_unitOfWork.TagRepository.Select());
        }

        [HttpPost]
        public ActionResult AddTag(int id, string ids)
        {
            Product product = _unitOfWork.ProductRepository.Select(c => c.ProductId == id, "ProductTags").FirstOrDefault();
            if (product != null)
            {
                while (product.ProductTags.Count > 0)
                    _unitOfWork.ProductTagRepository.Delete(product.ProductTags.First());

                if (!string.IsNullOrEmpty(ids))
                {
                    string[] s = ids.Split(',');
                    int guid;
                    List<int> list = (from s1 in s where int.TryParse(s1, out guid) select int.Parse(s1)).ToList();
                    IQueryable<Tag> tags = _unitOfWork.TagRepository.Select(c => list.Contains(c.TagId));
                    foreach (Tag tag in tags)
                    {
                        product.ProductTags.Add(new ProductTag
                        {
                            Product = product,
                            Tag = tag
                        });
                    }
                }
                _unitOfWork.AcceptChanges();
            }
            return Json(new
            {
                err = 0,
                module = "Product - Tag",
                msg = "Update Successfully"
            }, JsonRequestBehavior.DenyGet);
        }

        #endregion

        #region Image

        public ActionResult ProductImages(int id)
        {
            ViewBag.Id = id;
            return PartialView();
        }

        [GridAction]
        public ActionResult GetProductImageList(int id)
        {
            return View(new GridModel(_unitOfWork.ImageRepository.Select(c => c.ProductId == id).Select(c => new
            {
                c.Id,
                c.ImageName,
                c.Priority,
                IsBanner = c.IsBanner ?? false ? "checked" : "",
                c.Description
            })));
        }

        public ActionResult AddImage(int id)
        {
            return View(new ImageModel
            {
                ProductId = id
            });
        }

        [ValidateInput(false), HttpPost]
        public ActionResult AddImage(ImageModel imageModel)
        {
            if (ModelState.IsValid)
            {
                Image image = imageModel;
                if (_unitOfWork.ImageRepository.CheckInsertImage(image))
                {
                    Exception exception;
                    _unitOfWork.ImageRepository.Insert(image, out exception);
                    if (exception == null)
                    {
                        SaveResource("thumbnail", "Products", image);
                        image.ImageName = SaveBrushResource("thumbnail", "Products", image);
                        _unitOfWork.AcceptChanges();

                        ViewBag.Completed = true;
                    }
                }
            }
            return View(imageModel);
        }

        public ActionResult EditImage(string id)
        {
            int guid;
            if (int.TryParse(id, out guid))
            {
                Image image = _unitOfWork.ImageRepository.SelectbyId(guid);
                if (image != null)
                {
                    ImageModel imageModel = image;
                    return View(imageModel);
                }
            }
            return Content("");
        }

        [ValidateInput(false), HttpPost]
        public ActionResult EditImage(ImageModel imageModel)
        {
            if (ModelState.IsValid)
            {
                Image image = _unitOfWork.ImageRepository.SelectbyId(imageModel.Id);
                imageModel.Update(image);
                if (_unitOfWork.ImageRepository.CheckUpdateImage(image))
                {
                    Exception exception;
                    _unitOfWork.ImageRepository.Update(image, out exception);
                    if (exception == null)
                    {
                        SaveResource("thumbnail", "Products", image.ImageName, image);
                        image.ImageName = SaveBrushResource("thumbnail", "Products", image.ImageName, image);
                        _unitOfWork.AcceptChanges();

                        ViewBag.Completed = true;
                    }
                }
            }
            return View(imageModel);
        }

        [HttpPost]
        public ActionResult DeleteImage(string id)
        {
            if (id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s where int.TryParse(s1, out guid) select int.Parse(s1)).ToList();

                if (_unitOfWork.ImageRepository.CheckDeleteImage(list))
                {
                    _unitOfWork.ImageRepository.Delete(list, "Products", DeleteResource, DeleteBrushResource);
                }
            }
            return Json(new
            {
                err = 0,
                module = "Product - Image",
                msg = "Update Successfully"
            }, JsonRequestBehavior.DenyGet);
        }

        #endregion

        #region Property

        public ActionResult ProductProperties(int id)
        {
            ViewBag.Id = id;
            return PartialView();
        }

        [GridAction]
        public ActionResult GetPropertyList(int id)
        {
            return View(new GridModel(_unitOfWork.ProductPropertyRepository.Select(c => c.ProductId == id).Select(c => new
            {
                c.ProductPropertyId,
                c.Property.Name,
                c.Property.GroupName,
                Bit = c.Bit ?? false
                              ? "checked"
                              : "",
                c.Numer,
                c.Value
            })));
        }

        public ActionResult AddProperty(int id)
        {
            Product product = _unitOfWork.ProductRepository.SelectbyId(id);
            if (product != null)
            {
                ViewBag.Properties = _unitOfWork.CategoryPropertyRepository.Select(c => c.CategoryId == product.CategoryId).ToList().Select(c => new SelectListItem
                {
                    Text = c.Property.Name,
                    Value = c.Property.PropertyId + ""
                });
                return View(new ProductPropertyModel
                {
                    ProductId = id
                });
            }
            return Content("");
        }

        [ValidateInput(false), HttpPost]
        public ActionResult AddProperty(ProductPropertyModel productPropertyModel)
        {
            Product product = _unitOfWork.ProductRepository.SelectbyId(productPropertyModel.ProductId ?? 0);
            if (product != null)
            {
                if (ModelState.IsValid)
                {
                    ProductProperty productProperty = productPropertyModel;
                    if (_unitOfWork.ProductPropertyRepository.CheckInsertProductProperty(productProperty))
                    {
                        Exception exception;
                        _unitOfWork.ProductPropertyRepository.Insert(productProperty, out exception);
                        if (exception == null)
                        {
                            ViewBag.Completed = true;
                        }
                    }
                }
                ViewBag.Properties = _unitOfWork.CategoryPropertyRepository.Select(c => c.CategoryId == product.CategoryId).ToList().Select(c => new SelectListItem
                {
                    Text = c.Property.Name,
                    Value = c.Property.PropertyId + ""
                });
                return View(productPropertyModel);
            }
            return Content("");
        }

        public ActionResult EditProperty(string id)
        {
            int guid;
            if (int.TryParse(id, out guid))
            {
                ProductProperty productProperty = _unitOfWork.ProductPropertyRepository.Select(c => c.ProductPropertyId == guid, "Product").FirstOrDefault();
                if (productProperty != null)
                {
                    ViewBag.Properties = _unitOfWork.CategoryPropertyRepository.Select(c => c.CategoryId == productProperty.Product.CategoryId).ToList().Select(c => new SelectListItem
                    {
                        Text = c.Property.Name,
                        Value = c.Property.PropertyId + ""
                    });

                    ProductPropertyModel productPropertyModel = productProperty;
                    return View(productPropertyModel);
                }
            }
            return Content("");
        }

        [ValidateInput(false), HttpPost]
        public ActionResult EditProperty(ProductPropertyModel productPropertyModel)
        {
            Product product = _unitOfWork.ProductRepository.SelectbyId(productPropertyModel.ProductId ?? 0);
            if (product != null)
            {
                if (ModelState.IsValid)
                {
                    ProductProperty productProperty = _unitOfWork.ProductPropertyRepository.SelectbyId(productPropertyModel.ProductPropertyId);
                    productPropertyModel.Update(productProperty);
                    if (_unitOfWork.ProductPropertyRepository.CheckUpdateProductProperty(productProperty))
                    {
                        Exception exception;
                        _unitOfWork.ProductPropertyRepository.Update(productProperty, out exception);
                        if (exception == null)
                        {
                            ViewBag.Completed = true;
                        }
                    }
                }
                ViewBag.Properties = _unitOfWork.CategoryPropertyRepository.Select(c => c.CategoryId == product.CategoryId).ToList().Select(c => new SelectListItem
                {
                    Text = c.Property.Name,
                    Value = c.Property.PropertyId + ""
                });
                return View(productPropertyModel);
            }
            return Content("");
        }

        [HttpPost]
        public ActionResult DeleteProperty(string id)
        {
            UpdateResult result = new UpdateResult
            {
                err = 0,
                module = "Product - Property",
                msg = "Update Successfully"
            };
            if (id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s where int.TryParse(s1, out guid) select int.Parse(s1)).ToList();

                if (_unitOfWork.ProductPropertyRepository.CheckDeleteProductProperty(list))
                {
                    Exception exception;
                    _unitOfWork.ProductPropertyRepository.Delete(list, out exception);
                    if (exception != null)
                    {
                        result.err = 1;
                        result.msg = exception.StackTrace;
                    }
                }
                return Json(result, JsonRequestBehavior.DenyGet);
            }
            return Content("");
        }

        #endregion
    }
}
